package cn.edu.nwafu.mail.service.impl;

import cn.edu.nwafu.common.exception.BusinessException;
import cn.edu.nwafu.common.result.ResponseEnum;
import cn.edu.nwafu.mail.service.SendEmailService;
import cn.edu.nwafu.mail.util.ToEmail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
public class SendEmailServiceImpl implements SendEmailService {

    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private JavaMailSender mailSender;

    @Override
    public void sendEmail(String code,String mail) {
        ToEmail toEmail = new ToEmail(code);
        // 创建简单邮件消息
        SimpleMailMessage message = new SimpleMailMessage();
        // 发送方
        message.setFrom(from);
        // 收件方
        message.setTo(mail);
        // 邮件标题
        message.setSubject(ToEmail.SUBJECT);
        // 邮件内容
        message.setText(toEmail.getContent());

        try {
            mailSender.send(message);
        } catch (MailException e) {
            throw new BusinessException(ResponseEnum.SEND_MAIL_ERROR, e);
        }

    }
}
